package com.huluobo.a2202mvvm_im_douyindemo.chat;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.util.Log;
import android.view.View;

import com.huluobo.a2202mvvm_im_douyindemo.R;
import com.huluobo.a2202mvvm_im_douyindemo.adapter.MessageAdapter;
import com.huluobo.a2202mvvm_im_douyindemo.databinding.ActivityMyChatBinding;
import com.huluobo.a2202mvvm_im_douyindemo.mvvmBase.BaseMVVMActivity;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;

import java.util.ArrayList;
import java.util.List;

public class MyChatActivity extends BaseMVVMActivity<ActivityMyChatBinding, ChatViewModel> {
    private List<EMMessage> emMessageList = new ArrayList<>();
    private MessageAdapter messageAdapter;

    private String conversationId;
    private int chatType;

    private EMMessageListener emMessageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            runOnUiThread(() -> {
                emMessageList.addAll(messages);
                messageAdapter.notifyDataSetChanged();
                scrollToBottom();
            });
        }
    };

    @Override
    protected void initData() {
        viewModel.sendMessageSuccess.observe(this, emMessage -> {
            emMessageList.add(emMessage);
            messageAdapter.notifyDataSetChanged();
            dataBinding.chatInputEt.setText("");
            scrollToBottom();
        });

        viewModel.sendMessageFailed.observe(this, s -> {
            Log.i("TagA", "发送消息失败:" + s);
        });
    }

    private void scrollToBottom() {
        dataBinding.chatRv.smoothScrollToPosition(emMessageList.size() - 1);
    }

    @Override
    protected void intiView() {
        conversationId = getIntent().getExtras().getString("conversationId");
        chatType = getIntent().getExtras().getInt("chatType");

        dataBinding.chatHeader.headerTitleTv.setText(conversationId);
        dataBinding.chatHeader.headerBackIv.setVisibility(View.VISIBLE);
        dataBinding.chatHeader.headerBackIv.setOnClickListener(v -> {
            finish();
        });

        dataBinding.chatSendBtn.setOnClickListener(v -> {
            viewModel.sendMessage(
                    conversationId,
                    dataBinding.chatInputEt.getText().toString(),
                    chatType
            );
        });

        dataBinding.chatRv.setLayoutManager(new LinearLayoutManager(this));
        messageAdapter = new MessageAdapter(emMessageList);
        dataBinding.chatRv.setAdapter(messageAdapter);

        EMClient.getInstance().chatManager().addMessageListener(emMessageListener);

        if (EMClient.getInstance().chatManager().getConversation(conversationId) != null) {
            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationId);
            conversation.markAllMessagesAsRead();

            if (conversation.getAllMessages().size() != 0) {
                emMessageList.addAll(conversation.getAllMessages());
                messageAdapter.notifyDataSetChanged();
            }

            dataBinding.chatSrl.setOnRefreshListener(() -> {
                String startId = emMessageList.get(0).getMsgId();//查询历史消息记录的起始位置,也就是当前聊天数据源的底0位
                List<EMMessage> emMessages = conversation.loadMoreMsgFromDB(startId, 10);
                emMessageList.addAll(0, emMessages);//加载历史记录时,不能从list的末尾添加,也就是不能直接allAll,需要从list的头开始添加
                messageAdapter.notifyDataSetChanged();
                dataBinding.chatSrl.setRefreshing(false);
                dataBinding.chatRv.smoothScrollToPosition(emMessages.size()-1);
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(emMessageListener);
    }

    @Override
    protected Class<ChatViewModel> getViewModel() {
        return ChatViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_chat;
    }
}